import moviepy
from moviepy.editor import TextClip, CompositeVideoClip, VideoFileClip,ImageClip
import moviepy.editor as mp
import os
import moviepy.video.io.ImageSequenceClip
import logging
import random
# 配置日志
logging.basicConfig(filename='xiaoshuo_batch.log', format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)


class VideoPro:
    def __init__(self, filepath, background=None, log_picture=None):
        self.filepath = filepath
        self.clip = VideoFileClip(filepath)
        self.log_picture = log_picture
        self.background = background
        self.audio_clip = self.clip.audio
        self.work_path = os.getcwd()

    def add_china_text(self, china_text='我爱45oo你中国abc', fontsize=100):
        """
        给视频增加中文字幕
        :param china_text:
        :return:
        """
        txtClip = TextClip(china_text, color='black', font="KaiTi", kerning=5, fontsize=200)
        # 文本clip在屏幕正中显示持续10秒
        txt_clip = txtClip.set_pos('center').set_duration(self.clip.duration)

        # 把 text clip 的内容覆盖 video clip
        self.clip = CompositeVideoClip([self.clip, txt_clip])

    def add_log_picture(self):
        """
        增加log图片
        :return:
        """
        if self.log_picture is not None:
            logo = (mp.ImageClip(self.log_picture)
                    .set_duration(self.clip.duration)  # 水印持续时间
                    .resize(height=60)  # 水印的高度，会等比缩放
                    .margin(right=2, top=2, left=3, opacity=1)  # 水印边距和透明度
                    .resize(0.8)
                    .set_pos(("left", "top")))  # 水印的位置
            logo_height = self.clip.size[1] / self.log_rate
            logo = logo.resize(height=logo_height)

            self.clip = mp.CompositeVideoClip([self.clip, logo])

    def backgroup_audio_pro(self):
        if self.background is not None:
            self.image_to_video()
            # self.backgroup_audio = mp.CompositeVideoClip([self.img_video, self.audio_clip])
            self.backgroup_audio = self.img_video.set_audio(self.audio_clip)

    def save_backgroup_audio(self, out_file_path):
        self.backgroup_audio.write_videofile(out_file_path)

    def image_to_video(self):
        if self.background is not None:
            # fps = 10
            # ps_num = int(self.clip.duration * fps)
            # ps = [self.background for i in range(ps_num)]
            # self.img_video = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(ps, fps=fps)
            background_img = ImageClip(self.background).set_fps(24)
            self.img_video = background_img.set_duration(self.clip.duration)


def xiaoshuo_pro(filepath):
    cur_path = os.getcwd()
    b_pic = os.path.join(cur_path,"douluo_img")
    b_fps = [os.path.join(b_pic,duoluo_pic) for duoluo_pic in os.listdir(b_pic)]
    b_fp = random.choice(b_fps)
    logo_fp = os.path.join(cur_path, "source" + os.sep + "logo.png")
    path = filepath
    temp_path, filename = os.path.split(filepath)
    outpath = temp_path + "_out"
    if not os.path.exists(outpath):
        os.makedirs(outpath)
    outpath = os.path.join(outpath, filename)
    if not os.path.exists(outpath):
        VideoPro_obj = VideoPro(filepath=path, background=b_fp, log_picture=logo_fp)
        VideoPro_obj.backgroup_audio_pro()
        # VideoPro_obj.image_to_video()
        logging.info("xioashuo_pro saveing file :" + outpath)
        VideoPro_obj.save_backgroup_audio(outpath)
        logging.info("xioashuo_pro saved file :" + outpath)
    else:
        logging.info("xioashuo_pro haved file :" + outpath)


def sort_key(source:str):
    index,name  = source.split("_",maxsplit=2)
    return int(index)

if __name__ == '__main__':
    # b_fp = r"D:\python\python_code\video_edit\source\backgroup2.jpg"
    # logo_fp = r"D:\python\python_code\video_edit\source\logo.png"
    # path = r"D:\python\python_code\video_edit\myHolidays_edited.mp4"
    # outpath = r"D:\python\python_code\video_edit\out_test.mp4"
    # VideoPro_obj = VideoPro(filepath=path, background=b_fp, log_picture=logo_fp)
    # VideoPro_obj.backgroup_audio_pro()
    # # VideoPro_obj.image_to_video()
    # VideoPro_obj.save_backgroup_audio(outpath)
    in_path = r"/home/data/xigua/斗罗大陆2"
    video_file_temps = os.listdir(in_path)
    video_files = sorted(video_file_temps,key=sort_key)
    video_filepaths = [os.path.join(in_path,video_file) for video_file in video_files]
    logging.info("start xiaoshuo_pro :"+in_path)
    logging.info("total video:"+ str(len(video_files)))
    for video_filepath in video_filepaths:
        logging.info("xioashuo_pro file :" + video_filepath)
        xiaoshuo_pro(video_filepath)
